{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 热传导\n",
    "from collections import defaultdict\n",
    "import pandas as pd\n",
    "from tqdm import tqdm\n",
    "\n",
    "# 迭代的轮数。一轮迭代包括用户->物品和物品->用户两次扩散\n",
    "step=5\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "data=[\n",
    "    ['A','b'],\n",
    "    ['A','d'],\n",
    "    ['B','a'],\n",
    "    ['B','b'],\n",
    "    ['B','c'],\n",
    "    ['C','a'],\n",
    "    ['C','b'],\n",
    "    ['C','d'],\n",
    "    ['D','a'],\n",
    "    ['D','e']\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'A': {'b', 'd'}, 'B': {'a', 'b', 'c'}, 'C': {'a', 'b', 'd'}, 'D': {'a', 'e'}}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# user->item的映射\n",
    "# key：user\n",
    "# value：item的set\n",
    "train_data = {}\n",
    "\n",
    "for user, item in data:\n",
    "    train_data.setdefault(user,set())\n",
    "    train_data[user].add(item)\n",
    "train_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'b': {'A', 'B', 'C'},\n",
       " 'd': {'A', 'C'},\n",
       " 'a': {'B', 'C', 'D'},\n",
       " 'c': {'B'},\n",
       " 'e': {'D'}}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 建立item_user倒排表\n",
    "item_users = dict()\n",
    "for u, items in train_data.items():\n",
    "    for i in items:\n",
    "        if i not in item_users:\n",
    "            item_users[i] = set()\n",
    "        item_users[i].add(u)\n",
    "item_users"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|███████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 445.67it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A\n",
      "defaultdict(<class 'int'>, {'b': 0.5240636351801047, 'd': 0.5355584252591069, 'a': 0.47974814878321403, 'c': 0.5010740550221003, 'e': 0.41637374256973025})\n",
      "B\n",
      "defaultdict(<class 'int'>, {'b': 0.7031438865920675, 'd': 0.7015388735679265, 'a': 0.6980340876856508, 'c': 0.7063539126403494, 'e': 0.6870344173906415})\n",
      "C\n",
      "defaultdict(<class 'int'>, {'b': 0.8137913004453929, 'd': 0.8205891505359956, 'a': 0.7883473894562143, 'c': 0.8001956002641873, 'e': 0.7522100289590001})\n",
      "D\n",
      "defaultdict(<class 'int'>, {'e': 0.4882854176192653, 'a': 0.4205446694694237, 'b': 0.3750134289954106, 'd': 0.36528895096657016, 'c': 0.3944623850530915})\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "user_item = train_data\n",
    "rec_item = defaultdict(list)\n",
    "for u in tqdm(user_item):\n",
    "    print(u)\n",
    "    item_cnt = defaultdict(int)\n",
    "    user_cnt = defaultdict(int)\n",
    "    for i in user_item[u]:\n",
    "        item_cnt[i] = 1\n",
    "    for k in range(step*2):\n",
    "        if k % 2 == 1:\n",
    "            # 用户扩散项目\n",
    "            item_cnt = defaultdict(int)\n",
    "            for user in user_cnt:\n",
    "                for item in user_item[user]:\n",
    "                    item_cnt[item] += user_cnt[user] / len(item_users[item])\n",
    "#             print(item_cnt)\n",
    "\n",
    "        else:\n",
    "            # 项目扩散用户\n",
    "            user_cnt = defaultdict(int)\n",
    "            for item in item_cnt:\n",
    "                for user in item_users[item]:\n",
    "                    user_cnt[user] += item_cnt[item] / (len(user_item[user]))\n",
    "#             print(user_cnt)\n",
    "\n",
    "    res = ((pd.DataFrame(item_cnt, index=[0])).T).sort_values([0], ascending=[0]).index.tolist()\n",
    "\n",
    "    rec_item[u] = [i for i in res if i not in user_item[u]]\n",
    "    print(item_cnt)\n",
    "    \n",
    "    \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
